package com.ms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ms.dao.QuaApplicationMapper;
import com.ms.entity.QuaApplication;
import com.ms.entity.Organizer;
import com.ms.entity.Manager;
import com.ms.entity.Game;
import com.ms.service.inter.QuaApplicationService;
import com.ms.service.inter.GameService;
import com.ms.utils.SimpleTokenUtils;
import com.ms.utils.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 资格申请服务实现类
 * 实现资格申请相关业务逻辑
 */
@Service
public class QuaApplicationServiceImpl extends ServiceImpl<QuaApplicationMapper, QuaApplication> implements QuaApplicationService {

    @Autowired
    private GameService gameService;

    /**
     * 1. 提交申请材料
     * 保存用户提交的申请信息到数据库
     * 自动从token中获取举办方信息并填充
     */
    @Override
    public boolean submitApply(String token, QuaApplication quaApplication) {
        // 从token获取当前登录的举办方信息
        Object user = SimpleTokenUtils.getUserByToken(token);
        if (!(user instanceof Organizer)) {
            throw new RuntimeException("请使用举办方账号登录");
        }
        Organizer organizer = (Organizer) user;

        // 自动填充举办方ID
        quaApplication.setOrId(organizer.getOrId());
        // 设置默认状态为待审核(0)
        quaApplication.setApplyStatus((byte) 0);
        // 申请时间由MyBatis-Plus自动填充，这里可以不用设置

        return save(quaApplication);
    }

    /**
     * 2. 查询申请状态
     * 根据举办方ID获取其所有的申请信息
     */
    @Override
    public List<QuaApplication> getApplyStatusByOrganizer(Integer organizerId) {
        QueryWrapper<QuaApplication> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("or_id", organizerId);
        return list(queryWrapper);
    }

    /**
     * 获取所有申请状态（供管理员使用）
     * 未审批的结果显示在最上方，同审批结果的数据按日期从老到新排序
     */
    @Override
    public List<QuaApplication> getAllApplyStatusOrdered() {
        QueryWrapper<QuaApplication> queryWrapper = new QueryWrapper<>();
        // 按照申请状态升序排列（未审核=0在前，已审核=1/2在后）
        // 相同状态下按申请时间升序排列（老的在前）
        queryWrapper.orderByAsc("apply_status", "apply_time");
        return list(queryWrapper);
    }

    /**
     * 3. 对资格申请进行审批处理
     * 管理员审核申请并更新审核结果
     */
    @Override
    public boolean feedbackApplyResult(QuaApplication quaApplication) {
        // 获取当前登录的管理员信息
        Manager manager = UserContext.getManager();
        if (manager == null) {
            throw new RuntimeException("管理员未登录");
        }

        // 自动填充审核信息
        quaApplication.setMaId(manager.getMaId());
        quaApplication.setAuditTime(LocalDateTime.now());

        // 验证状态值是否合法
        if (quaApplication.getApplyStatus() == null
                || (quaApplication.getApplyStatus() != 1 && quaApplication.getApplyStatus() != 2)) {
            throw new RuntimeException("无效的审核状态，必须是1(通过)或2(驳回)");
        }

        // 驳回时必须填写审核意见
        if (quaApplication.getApplyStatus() == 2 &&
                (quaApplication.getAuditOpinion() == null || quaApplication.getAuditOpinion().trim().isEmpty())) {
            throw new RuntimeException("驳回申请必须填写审核意见");
        }

        // 如果审批通过，则创建对应的Game对象
        if (quaApplication.getApplyStatus() == 1) {
            // 查询完整的申请信息
            QuaApplication fullQuaApplication = getById(quaApplication.getQuaId());
            
            // 创建新的Game对象
            Game game = new Game();
            game.setOrId(fullQuaApplication.getOrId());
            game.setGameName(fullQuaApplication.getGamesName());
            game.setCreateTime(new java.util.Date());
            game.setQuaId(fullQuaApplication.getQuaId()); // 设置审批记录ID
            
            // 保存Game对象
            gameService.save(game);
        }

        return updateById(quaApplication);
    }
}